/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXQt - a lightweight, Qt based, desktop toolset
 * https://lxqt.org
 *
 * Copyright: 2015 LXQt team
 * Authors:
 *  Balázs Béla <balazsbela[at]gmail.com>
 *  Paulo Lieuthier <paulolieuthier@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */
#include "statusnotiferscrollarea.h"
#include <QGuiApplication>
#include <QScreen>
#define CONFIG_FILE_BACKUP     "/usr/share/ukui/panel.conf"

StatusNotiferScrollArea::StatusNotiferScrollArea(IUKUIPanelPlugin *plugin, QWidget *parent)
    :m_plugin(plugin),
     m_parent(parent)
{
    //检查配置文件是否完整
    QSettings backup_qsettings(CONFIG_FILE_BACKUP,QSettings::IniFormat);
    QStringList showAppBackup = backup_qsettings.value("statusnotifier/showApp").toStringList();
    QStringList hideAppBackup = backup_qsettings.value("statusnotifier/hideApp").toStringList();
    QStringList fixedAppBackup = backup_qsettings.value("statusnotifier/fixedApp").toStringList();
    QString alignmentBackup = backup_qsettings.value("statusnotifier/alignment").toString();
    PluginSettings *settings = m_plugin->settings();  // ~/.config/ukui/panel.conf
    QStringList allkeys = settings->allKeys();
    if(!allkeys.contains("showApp")) {
        settings->setValue("showApp",showAppBackup);
    }
    if(!allkeys.contains("hideApp")) {
        settings->setValue("hideApp",hideAppBackup);
    }
    if(!allkeys.contains("fixedApp")) {
        settings->setValue("fixedApp",fixedAppBackup);
    }
    QStringList showApp = settings->value("showApp").toStringList();
    QStringList hideApp = settings->value("hideApp").toStringList();
    for(int i=0; i<fixedAppBackup.size(); i++) {
        QString str = fixedAppBackup.at(i);
        showApp.removeOne(str);
        hideApp.removeOne(str);
    }
    settings->setValue("showApp",showApp);
    settings->setValue("hideApp",hideApp);
    if(!allkeys.contains("alignment")) {
        settings->setValue("alignment",alignmentBackup);
    }

    //监听托盘应用注册
    m_watcher = new StatusNotifierWatcher;
    connect(m_watcher, &StatusNotifierWatcher::StatusNotifierItemRegistered,
            this, &StatusNotiferScrollArea::itemAdded);
    connect(m_watcher, &StatusNotifierWatcher::StatusNotifierItemUnregistered,
            this, &StatusNotiferScrollArea::itemRemoved);

    //设置滚动区域属性
    this->setWidgetResizable(true);
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setProperty("drawScrollBarGroove",false);
    this->verticalScrollBar()->setProperty("drawScrollBarGroove",false);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->verticalScrollBar()->setVisible(false);
    this->setFrameShape(QFrame::NoFrame);
    this->setAlignment(Qt::AlignRight);
    this->setContentsMargins(0,0,0,0);
    //滚动区域背景透明
    QPalette pal = this->palette();
    pal.setBrush(QPalette::Window, QColor(Qt::transparent));
    this->setPalette(pal);

    //最外层窗口布局
    m_outWidget = new QWidget(this);
    m_outWidget->setContentsMargins(0,0,0,0);
    m_outLayout = new QGridLayout(m_outWidget);
    m_outLayout->setContentsMargins(0,0,0,0);
    m_outLayout->setSpacing(0);
    m_outWidget->setLayout(m_outLayout);
    this->setWidget(m_outWidget);


    //托盘窗口和布局
    m_statusNotifierWidget = new QWidget(this);
    m_arrowBtn = new StatusNotifierStorageArrow(m_plugin, m_statusNotifierWidget);
    connect(m_arrowBtn,SIGNAL(addButton(StatusNotifierButtonAbstract*,StatusNotifierButtonAbstract*)),
                this,SLOT(arrowbtnAddButton(StatusNotifierButtonAbstract*,StatusNotifierButtonAbstract*)));
    m_layout = new UKUi::GridLayout(m_statusNotifierWidget);
    m_layout->setDirection(UKUi::GridLayout::LeftToRight);
    m_layout->setContentsMargins(0, 0, 0, 0);
    m_statusNotifierWidget->setLayout(m_layout);
    m_layout->addWidget(m_arrowBtn);

    //托盘区固定应用窗口和布局
    m_statusNotifierFixedWidget = new QWidget(this);
    m_statusNotifierFixedWidget->setAcceptDrops(false);
    m_layoutFix = new UKUi::GridLayout(m_statusNotifierFixedWidget);
    m_layoutFix->setDirection(UKUi::GridLayout::LeftToRight);
    m_layoutFix->setContentsMargins(0, 0, 0, 0);
    m_statusNotifierFixedWidget->setLayout(m_layoutFix);

    //监听托盘图标隐藏
    const QByteArray id(UKUI_PANEL_SETTINGS);
    if(QGSettings::isSchemaInstalled(id)) {
        m_gsettings = new QGSettings(id);
        connect(m_gsettings, &QGSettings::changed, this, [=] (const QString &key) {
            if(key==SHOW_STATUSNOTIFIER_BUTTON) {
                exchangeHideAndShow();
            }
        });
    }
}

StatusNotiferScrollArea::~StatusNotiferScrollArea()
{
    if(m_watcher) {
        delete(m_watcher);
        m_watcher = NULL;
    }
    if(m_gsettings) {
        delete(m_gsettings);
        m_gsettings = NULL;
    }
}

void StatusNotiferScrollArea::realign()
{
    m_layout->setEnabled(false);
    m_layoutFix->setEnabled(false);
    m_outLayout->setEnabled(false);
    IUKUIPanel *panel = m_plugin->panel();
    if (panel->isHorizontal()) {
        //更新托盘活动区大小
        m_layout->setRowCount(panel->lineCount());
        m_layout->setColumnCount(0);
        m_layout->setEnabled(true);
        int widgetWidth;
        if(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool()) {
            widgetWidth = (m_activeButtons.size()+1)*uint(panel->panelSize()*0.7);
        } else {
            widgetWidth = (m_activeButtons.size()-m_hideButtons.size()+1)*uint(panel->panelSize()*0.7);
        }
        m_statusNotifierWidget->setFixedSize(widgetWidth, panel->panelSize());
        int margins = panel->panelSize()*0.15;
        m_statusNotifierWidget->setContentsMargins(0,margins,0,margins);

        //更新托盘固定区大小
        m_layoutFix->setRowCount(panel->lineCount());
        m_layoutFix->setColumnCount(0);
        m_layoutFix->setEnabled(true);
        int fixedWidgetWidth;
        fixedWidgetWidth = (m_fixedButtons.size())*uint(panel->panelSize()*0.7);
        m_statusNotifierFixedWidget->setFixedSize(fixedWidgetWidth, panel->panelSize());
        m_statusNotifierFixedWidget->setContentsMargins(0,margins,0,margins);

        //更新外层大窗口大小和布局
        m_outLayout->setAlignment(Qt::AlignRight);
        m_outLayout->addWidget(m_statusNotifierWidget,0,0);
        m_outLayout->addWidget(m_statusNotifierFixedWidget,0,1);
        m_outLayout->setEnabled(true);
        m_outWidget->setFixedSize(widgetWidth+fixedWidgetWidth, panel->panelSize());
        if((widgetWidth+fixedWidgetWidth) > QGuiApplication::primaryScreen()->geometry().width()/3) {
            //托盘区超过屏幕宽度1/3，超出量不到一个图标宽度的，正常显示，否则托盘显示区为屏幕宽度1/3
            if(widgetWidth+fixedWidgetWidth-QGuiApplication::primaryScreen()->geometry().width()/3 < uint(panel->panelSize()*0.7)) {
                this->setFixedSize(widgetWidth+fixedWidgetWidth, panel->panelSize());
            } else {
                this->setFixedSize(QGuiApplication::primaryScreen()->geometry().width()/3, panel->panelSize());
            }
        } else {
            this->setFixedSize(widgetWidth+fixedWidgetWidth, panel->panelSize());
        }
    } else {
        //更新托盘活动区大小
        m_layout->setColumnCount(panel->lineCount());
        m_layout->setRowCount(0);
        m_layout->setEnabled(true);
        int heightWidth;
        if(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool()) {
            heightWidth = (m_activeButtons.size()+1)*uint(panel->panelSize()*0.7);
        } else {
            heightWidth = (m_activeButtons.size()-m_hideButtons.size()+1)*uint(panel->panelSize()*0.7);
        }
        m_statusNotifierWidget->setFixedSize(panel->panelSize(), heightWidth);
        int margins = panel->panelSize()*0.15;
        m_statusNotifierWidget->setContentsMargins(margins,0,margins,0);

        //更新托盘固定区大小
        m_layoutFix->setColumnCount(panel->lineCount());
        m_layoutFix->setRowCount(0);
        m_layoutFix->setEnabled(true);
        int fixedWidgetHeight;
        fixedWidgetHeight = (m_fixedButtons.size())*uint(panel->panelSize()*0.7);
        m_statusNotifierFixedWidget->setFixedSize(panel->panelSize(), fixedWidgetHeight);
        m_statusNotifierFixedWidget->setContentsMargins(margins,0,margins,0);

        //更新外层大窗口大小和布局
        m_outLayout->setAlignment(Qt::AlignBottom);
        m_outLayout->addWidget(m_statusNotifierWidget,0,0);
        m_outLayout->addWidget(m_statusNotifierFixedWidget,1,0);
        m_outLayout->setEnabled(true);
        m_outWidget->setFixedSize(panel->panelSize(), heightWidth+fixedWidgetHeight);
        if((heightWidth+fixedWidgetHeight) > QGuiApplication::primaryScreen()->geometry().height()/3) {
            this->setFixedSize(panel->panelSize(), QGuiApplication::primaryScreen()->geometry().height()/3);
        } else {
            this->setFixedSize(panel->panelSize(), heightWidth+fixedWidgetHeight);
        }
    }
}

void StatusNotiferScrollArea::wheelEvent(QWheelEvent *event)
{
    if(this->horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
        if(event->delta() >= 0) {
            this->horizontalScrollBar()->setValue(horizontalScrollBar()->value()-40);
        } else {
            this->horizontalScrollBar()->setValue(horizontalScrollBar()->value()+40);
        }
    }
    if(this->verticalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) {
        if(event->delta() >= 0) {
            this->verticalScrollBar()->setValue(verticalScrollBar()->value()-40);
        } else {
            this->verticalScrollBar()->setValue(verticalScrollBar()->value()+40);
        }
    }
}

void StatusNotiferScrollArea::itemAdded(QString serviceAndPath)
{
    //判断DISPLAY
    if(serviceAndPath.contains("org.kde.StatusNotifierItem")) {
        QStringList strList = serviceAndPath.split("-");
        QString displayNum = getDisplayId(strList.at(1));
        QString envDisplay = getenv("DISPLAY");
        if(envDisplay != displayNum) {
            qInfo()<<"The application displayNum is inconsistent with the envDisplay";
            return;
        }
    }

    int slash = serviceAndPath.indexOf('/');
    QString serv = serviceAndPath.left(slash);
    QString path = serviceAndPath.mid(slash);
    StatusNotifierButton *button = new StatusNotifierButton(serv, path, m_plugin, m_statusNotifierWidget);
    button->setFoldState(!m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool());
    m_services.insert(serviceAndPath, button);
    connect(button, SIGNAL(switchButtons(StatusNotifierButtonAbstract*,StatusNotifierButtonAbstract*)),
                this, SLOT(switchButtons(StatusNotifierButtonAbstract*,StatusNotifierButtonAbstract*)));
    connect(button,&StatusNotifierButton::layoutUpdate,this,[=]() {
        resetLayout();
    });
    connect(button,&StatusNotifierButton::layoutReady,this,[=]() {
        if(button->m_iconStatus && !button->m_id.isEmpty()) {  //Icon和ID都准备好后再加入布局
            QStringList fixedAppList = readFixedAppSettings();
            if(fixedAppList.contains(button->m_id)) {
                m_statusNotifierFixedButtons.append(button);
            } else {
                m_statusNotifierButtons.append(button);
            }
            resetLayout();
        }
    });
}

void StatusNotiferScrollArea::itemRemoved(const QString &serviceAndPath)
{
    StatusNotifierButton *button = m_services.value(serviceAndPath, NULL);
    if (button) {
        disconnect(button,&StatusNotifierButton::layoutReady,0,0);
        if(m_statusNotifierButtons.contains(button)) {
            m_statusNotifierButtons.removeOne(button);
            m_layoutButtons.remove(button->m_id);
            m_activeButtons.remove(button->m_id);
            m_layout->removeWidget(button);
        } else if(m_statusNotifierFixedButtons.contains(button)) {
            m_statusNotifierFixedButtons.removeOne(button);
            m_fixedButtons.remove(button->m_id);
            m_layoutFix->removeWidget(button);
        }
        m_services.remove(serviceAndPath);
        resetLayout();
        button->deleteLater();
    }
}

void StatusNotiferScrollArea::resetLayout()
{
    //更新托盘活动区布局
    QStringList show=readSettings().at(0);
    show.removeAll("");
    QStringList hide=readSettings().at(1);
    hide.removeAll("");
    QStringList fixed=readFixedAppSettings();
    fixed.removeAll("");
    m_activeButtons.clear();
    m_layoutButtons.clear();
    for(int i=0;i<m_statusNotifierButtons.size();i++) {
        if(m_statusNotifierButtons.at(i)) {
            m_layoutButtons.insert(m_statusNotifierButtons.at(i)->m_id,m_statusNotifierButtons.at(i));
            if(m_statusNotifierButtons.at(i)->isVisible()) {
                m_activeButtons.insert(m_statusNotifierButtons.at(i)->m_id,m_statusNotifierButtons.at(i));
                if((!show.contains(m_statusNotifierButtons.at(i)->m_id))&&(!hide.contains(m_statusNotifierButtons.at(i)->m_id))
                        &&(!fixed.contains(m_statusNotifierButtons.at(i)->m_id))) {
                    if(m_statusNotifierButtons.at(i)->m_id=="") {
                        continue;
                    }
                    hide.append(m_statusNotifierButtons.at(i)->m_id);
                    qCritical()<<"config change resetLayout:id tooltoptitle:"
                            <<m_statusNotifierButtons.at(i)->m_id
                            <<m_statusNotifierButtons.at(i)->m_toolTipTitle;
                    saveSettings("",m_statusNotifierButtons.at(i)->m_id);
                    continue;
                }
            }
        }
        else {
            qDebug()<<"m_statusNotifierButtons add error   :  "<<m_statusNotifierButtons.at(i);
        }
    }
    m_hideButtons.clear();
    for(int i=0;i<hide.size();i++) {
        if(!m_activeButtons.value(hide.at(i))==NULL) {
            m_activeButtons.value(hide.at(i))->setVisible(m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool());
            m_activeButtons.value(hide.at(i))->setActionArea(STORAGE);
            m_layout->addWidget(m_activeButtons.value(hide.at(i)));
            m_hideButtons.insert(hide.at(i),m_activeButtons.value(hide.at(i)));
        }
    }
    m_layout->addWidget(m_arrowBtn);
    m_showButtons.clear();
    for(int i=0;i<show.size();i++) {
        if(!m_activeButtons.value(show.at(i))==NULL) {
            if(m_activeButtons.keys().contains(show.at(i))) {
                m_activeButtons.value(show.at(i))->setActionArea(SHOW);
                m_layout->addWidget(m_activeButtons.value(show.at(i)));
                m_showButtons.insert(show.at(i),m_activeButtons.value(show.at(i)));
            }
        }
    }
    m_layout->setEnabled(true);

    //更新托盘固定区布局
    for(int i=0;i<m_statusNotifierFixedButtons.size();i++) {
        if(m_statusNotifierFixedButtons.at(i)) {
            m_fixedButtons.insert(m_statusNotifierFixedButtons.at(i)->m_id,m_statusNotifierFixedButtons.at(i));
        }
    }
    for(int i=0;i<m_fixedButtons.size();i++) {
        if(!m_fixedButtons.value(fixed.at(i))==NULL) {
            m_fixedButtons.value(fixed.at(i))->setAcceptDrops(false);
            m_fixedButtons.value(fixed.at(i))->setVisible(true);
            m_layoutFix->addWidget(m_fixedButtons.value(fixed.at(i)));
        }
    }
    realign();
}

void StatusNotiferScrollArea::switchButtons(StatusNotifierButtonAbstract *srcButton,
                                            StatusNotifierButtonAbstract *dstButton)
{
    if (srcButton == dstButton)
        return;

    int srcIndex = m_layout->indexOf(srcButton);
    int dstIndex = m_layout->indexOf(dstButton);
    if (dstIndex == srcIndex || m_layout->animatedMoveInProgress()) {
        return;
    }

    StatusNotifierButton *src_item = nullptr;
    StatusNotifierButton *dst_item = nullptr;
    StatusNotifierStorageArrow *dst_arrow = nullptr;

    if(dstButton->getTypeName() == "Item") {
        dst_item = qobject_cast<StatusNotifierButton *>(dstButton);
    } else if(dstButton->getTypeName() == "StorageArrow") {
        exchangeHideAndShow();
        dst_arrow = qobject_cast<StatusNotifierStorageArrow *>(dstButton);
    }

    if(srcButton->getTypeName() == "Item") {
        src_item = qobject_cast<StatusNotifierButton *>(srcButton);
    }

    m_layout->moveItem(srcIndex, dstIndex, true);

    if(dst_arrow) {
        saveSettings(src_item->m_id,QString());
    } else {
        saveSettings(src_item->m_id,dst_item->m_id);
    }
}

void StatusNotiferScrollArea::saveSettings(QString button1,QString button2)
{
    PluginSettings *settings=m_plugin->settings();
    QStringList showApp=settings->value("showApp").toStringList();
    QStringList hideApp=settings->value("hideApp").toStringList();

    if(button2==NULL) {
        if(showApp.contains(button1)) {
            showApp.removeAll(button1);
            hideApp.append(button1);
        } else if(hideApp.contains(button1)) {
            hideApp.removeAll(button1);
            showApp.insert(0,button1);
        }
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
        return;
    }

    if(button1==NULL) {
        if(!button2.isNull()) {
            hideApp.append(button2);
            hideApp.removeAll("");
            settings->setValue("hideApp",hideApp);
            return;
        }
    }

    if(showApp.contains(button1)&&showApp.contains(button2)) {
        showApp.move(showApp.indexOf(button1), showApp.indexOf(button2));
        settings->setValue("showApp",showApp);
    }

    if(showApp.contains(button1)&&hideApp.contains(button2)) {
        hideApp.insert(hideApp.indexOf(button2),button1);
        showApp.removeAll(button1);
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
    }


    if(hideApp.contains(button1)&&showApp.contains(button2)) {
        showApp.insert(showApp.indexOf(button2),button1);
        hideApp.removeAll(button1);
        settings->setValue("showApp",showApp);
        settings->setValue("hideApp",hideApp);
    }
    if(hideApp.contains(button1)&&hideApp.contains(button2)) {
        hideApp.move(hideApp.indexOf(button1), hideApp.indexOf(button2));
        settings->setValue("hideApp",hideApp);
    }
    resetLayout();
}

QList<QStringList> StatusNotiferScrollArea::readSettings()
{
    PluginSettings *settings=m_plugin->settings();
    QStringList showApp=settings->value("showApp").toStringList();
    QStringList hideApp=settings->value("hideApp").toStringList();
    QList<QStringList> list;
    list.append(showApp);
    list.append(hideApp);
    return list;
}

QStringList StatusNotiferScrollArea::readFixedAppSettings()
{
    PluginSettings *settings = m_plugin->settings();
    QStringList fixedApp = settings->value("fixedApp").toStringList();
    return fixedApp;
}

void StatusNotiferScrollArea::exchangeHideAndShow()
{
    QMap<QString,StatusNotifierButton*> hideButtons;
    QStringList hide=readSettings().at(1);
    hide.removeAll("");
    for(int i=0;i<hide.size();i++) {
        if(!m_layoutButtons.value(hide.at(i))==NULL) {
            hideButtons.insert(hide.at(i),m_layoutButtons.value(hide.at(i)));
        }
    }

    QMap<QString, StatusNotifierButton*>::const_iterator i;
    for(i=hideButtons.constBegin();i!=hideButtons.constEnd();++i) {
        if(i.value()->getStatus()!=PASSIVE) {
            bool status = m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool();
            i.value()->setVisible(status);
        }
    }

    bool status = m_gsettings->get(SHOW_STATUSNOTIFIER_BUTTON).toBool();
    for(int i=0;i<m_statusNotifierButtons.size();i++) {
        m_statusNotifierButtons.at(i)->setFoldState(!status);
    }

    resetLayout();
}


void StatusNotiferScrollArea::arrowbtnAddButton(StatusNotifierButtonAbstract *srcButton,
                                                StatusNotifierButtonAbstract *dstButton)
{
    if (srcButton == dstButton)
        return;
    int srcIndex = m_layout->indexOf(srcButton);
    int dstIndex = m_layout->indexOf(dstButton);
    if (dstIndex == srcIndex || m_layout->animatedMoveInProgress()) {
        return;
    }

    switchButtons(srcButton,dstButton);
    resetLayout();
}

QString StatusNotiferScrollArea::getDisplayId(QString pid)
{
    //从 /proc/$pid/environ 中获取 DISPLAY 字段信息，此方案不适用于wayland
    QString environPath = "/proc/" + pid + "/environ";
    QFile envFile(environPath);
    if(envFile.open(QIODevice::ReadOnly)) {
        QByteArray array = envFile.readAll();
        array.replace('\0','#');
        QStringList list = QString(array).split("#");
        for(int i=0; i<list.size(); i++) {
            QString str = list.at(i);
            if(str.contains("DISPLAY=")) {
                QStringList list = str.split("=");
                qInfo()<<"DISPLAY :"<<list.at(1);
                return list.at(1);
            }
        }
        qInfo()<<"No find DISPLAY ";
        return QString(getenv("DISPLAY"));
    } else {
        qInfo()<<environPath << " open failed!";
        return QString(getenv("DISPLAY"));
    }
}



